# -*- coding: utf-8 -*-
import os
import sys

base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base.settings")

from common import orm
from common.lottery.model import TrackIndex
from common.lottery import KEYWORD_TYPE_DCT
from common.lottery.cyclical.model import ORDER_MODEL
from common.lottery.db import generate_track_detail

lottery_key = sys.argv[1]
user_id = sys.argv[2]
activity_type = KEYWORD_TYPE_DCT[lottery_key]
order_table = ORDER_MODEL[activity_type]

track_id_in_order = orm.session.query(order_table.track_id) \
    .filter(order_table.user_id == user_id) \
    .group_by(order_table.track_id).all()

track_id_in_index = orm.session.query(TrackIndex.track_id) \
    .filter(TrackIndex.user_id == user_id) \
    .group_by(TrackIndex.track_id).all()

for result in track_id_in_order:
    track_id = result[0]
    if track_id and result not in track_id_in_index:
        print('track_index missing: %s' % track_id)

        inst = TrackIndex()
        inst.activity_type = activity_type
        inst.user_id = user_id
        inst.track_id = track_id
        inst.save()
        generate_track_detail(track_id)
